package cn.tao.org.controller;



import cn.tao.org.domain.Employee;
import cn.tao.org.query.EmployeeQuery;
import cn.tao.org.service.IEmployeeService;
import cn.tao.utils.AjaxResult;
import cn.tao.utils.QueryResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@RestController
@RequestMapping("/employee")
//@CrossOrigin
public class EmployeeController {

    @Autowired
    private IEmployeeService employeeService;

    /**
     * 用户激活接口
     * @param
     * @return
     */
    @GetMapping("/put/{id}")
    public AjaxResult put(@PathVariable Long id){
        try {
            employeeService.uptState(id);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage(e.getMessage());
        }
    }

    /**
     * 新增和修改
     * @RequestBody 接收一个json类型的对象
     * @param employee
     * @return
     */
    @PutMapping
    public AjaxResult savAndUpt(@RequestBody Employee employee){
        try {
            if (employee.getId() == null){
                employeeService.save(employee);
            }else {
                employeeService.update(employee);
            }
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage(e.getMessage());
        }
    }

    /**
     *("/{id}"):要与@PathVariable中的参数对应
     * @param id
     * @return
     */
    @DeleteMapping("/{id}")
    public AjaxResult delById(@PathVariable("id") Long id){
        try{
            employeeService.delete(id);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage(e.getMessage());
        }
    }

    /**
     * 根据id查询一个
     * @param id
     * @return
     */
    @GetMapping("/{id}")
    public Employee findEmployeeById(@PathVariable("id") Long id){
        return employeeService.loadById(id);
    }



    /**
     * 查询所有
     * @return
     */
    @GetMapping
    public List<Employee> findEmployees(){
       return employeeService.loadAll();
    }


    /**
     * 高级查询和分页
     * @param query
     * @return
     */
    @PostMapping
    public QueryResult<Employee> findEmployeeByQuery(@RequestBody EmployeeQuery query){

        return employeeService.findByQuery(query);
    }

    /**
     * 批量删除
     * @param ids
     * @return
     */
    @PatchMapping
    public AjaxResult batchDelete(@RequestBody Long[] ids){
        try {
            employeeService.batchDelete(ids);
            return AjaxResult.me();
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResult.me().setMessage(e.getMessage());
        }
    }
}
